package project.controller;

import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import project.common.RecordNotFoundException;
import project.dto.RoomDTO;
import project.model.Room;
import project.model.RoomCategory;
import project.services.InventoryService;
import project.services_impl.InventoryServiceImpl;
/**
 * Resource (controller) class for {@link Room}s 
 * @author admin
 */
@RestController
@RequestMapping("rooms")
public class RoomResource {

	//Default initialization.
	@Autowired
	private InventoryService inventoryService;
	
	public RoomResource() {
	}
	public RoomResource(InventoryService inventoryService) {
		//Customized initialization.
		this.inventoryService = inventoryService;
	}
	
	@RequestMapping(value={"/","index"})
	public ModelAndView index(){
		System.out.println("Index page is being called!");
		ModelAndView view = new ModelAndView("index");
//		try{
//			//inventoryService.getRoomById(1);
//			inventoryService.save();
//			System.out.println("trying!");
//		}catch(RecordNotFoundException e)
//		{
//			inventoryService.save();
//			System.out.println("Catching Exception!");
//		}
		return view;
	}
	
	@RequestMapping(value="/{roomId}",method=RequestMethod.GET)
	public RoomDTO getRoom(@PathVariable("room_id")int roomId){
		Room room = inventoryService.getRoomById(roomId);
		return new RoomDTO(room);
	}
	/**
	 * Request to URLs, such as http://localhost:8080/rooms?room_category_id=1, will be handled by this method.
	 * The method will return a list of rooms for given category in JSON format.
	 * @param categoryId
	 * @return a List of rooms.
	 */
	@RequestMapping(method=RequestMethod.GET)
	public java.util.List<RoomDTO> getRoomsInCategory(@RequestParam("room_category_id") int categoryId){
		RoomCategory category = inventoryService.getRoomCategory(categoryId);
		//stream is the feature of Java8(check your favorite to know the details),while "::" stands for a quotation of method(here "new" means quotation of its constructor method)
		//by method map(RoomDTO::new) we initialize every Object of class "Room" in List<Room> with new instances
		return inventoryService.getAllRoomWithCategory(category).stream().map(RoomDTO::new).collect(Collectors.toList());
	}
}